import aiomysql
import asyncio

class Mysql(object):
	def __init__(self, host='localhost', user=None, passwd=None, port=3306, db='wordbook'):
		self.config = {
			'host': host,
			'user': user,
			'password': passwd,
			'port': port,
			'db': db,
			'connect_timeout': 10
		}

	async def AddOneWord(self, word, en_ph, us_ph, comment=''):
		if (self._pool is None):
			self._pool = await aiomysql.create_pool(**self.config)
		cmd = 'SELECT id from en_words where data="{}"'
        async with self._pool.get() as conn:
            async with conn.cursor() as cur:
                await cur.execute(cmd, word)
                r = await cur.fetchall()
                if len(r) != 0:
                	raise Exception("The word is added before!")
            async with conn.cursor() as cur:
            	cmd = 'INSERT INTO en_words (data, en_ph, us_ph, comment) VALUES ("{}", "{}", "{}", "{}")'
            	await cur.execute(cmd, word)
                r = await cur.fetchall()

if __name__ == '__main__':
	loop = asyncio.get_event_loop()
	m = Mysql('45.63.120.27','root','1havetof1ght')
	loop.run_until_complete(m.AddOneWord('1','2','3'))

